package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.entity.system.Setting;
import cn.livingCloud.entity.user.Member;
import cn.livingCloud.repository.MemberMapper;
import cn.livingCloud.repository.SettingMapper;
import cn.livingCloud.wechat.handler.WechatUserInfoHandler;
import cn.livingCloud.wechat.protocol.WechatAccessToken;
import cn.livingCloud.wechat.protocol.WechatUserInfo;
import cn.livingCloud.wechat.protocol.req.SubscribePushMsg;

import java.util.Date;

/**
 * Created by 唐旭 on 2016/1/4.
 */
public class MemberCreater {
    private transient MemberMapper mapper = BeanProvider.getBean(MemberMapper.class);
    private transient SettingMapper settingMapper = BeanProvider.getBean(SettingMapper.class);
    private SubscribePushMsg subscribePushMsg;

    public MemberCreater(SubscribePushMsg subscribePushMsg) {
        this.subscribePushMsg = subscribePushMsg;
    }

    /**
     * 根据openid查询系统是否存在该会员
     * 如果不存在则创建一个会员
     */
    public void create() {
        String openid = subscribePushMsg.getFromUserName();
        Member member = mapper.findMemberByOpenid(openid);
        if (member != null) {
            return;
        }
        Setting setting = settingMapper.findSetting();
        WechatUserInfoHandler handler = new WechatUserInfoHandler();
        WechatUserInfo info = handler.getUserInfo(WechatAccessToken.getInstance(), openid, setting.getAppid(), setting.getSecret());
        member = new Member(info)
                .setState(true)
                .setCreateTime(new Date());
        mapper.save(member);
    }
}
